package org.spring.boot.multiple.mybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: eastcom
 * @desc:
 **/
@Configuration("irmsDataSourceConfig")
@MapperScan(basePackages = {IrmsDataSourceConfig.IRMS_BASE_PACKAGES},
		sqlSessionFactoryRef = "irmsSqlSessionFactory")
public class IrmsDataSourceConfig {


	static final String IRMS_MAPPER_LOCATIONS = "classpath:org/spring/boot/multiple/mybatis/mapper/irms/*.xml";

	static final String IRMS_BASE_PACKAGES = "org.spring.boot.multiple.mybatis.dao.irms";

	@Bean(name="irmsDataSource")
	@Qualifier("irmsDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.irms")
	public DataSource getIrmsDataSource(){
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "irmsTransactionManager")
	public DataSourceTransactionManager getIrmsDataSourceTransactionManager() {
		return new DataSourceTransactionManager(this.getIrmsDataSource());
	}

	@Bean(name="irmsSqlSessionFactory")
	public SqlSessionFactory getIrmsSqlSessionFactory(@Qualifier("irmsDataSource") DataSource dataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		sessionFactory.setMapperLocations(resourcePatternResolver.getResources(IrmsDataSourceConfig.IRMS_MAPPER_LOCATIONS));
		return sessionFactory.getObject();
	}
}
